/* Copyright (c) 2004-2023 Peigen.info. All rights reserved. */
package info.peigen.hotpot.manage.core.util;

import cn.hutool.core.util.ObjectUtil;
import info.peigen.hotpot.common.core.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.core.handle.Context;

/**
 * <b>(ServletUtil)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2024/7/11
 */
@Slf4j
public class ServletUtil {
    public static String getParamFromRequest(String paramName) {
        Context request = getRequest();

        // 1. 尝试从请求体里面读取
        String paramValue = request.param(paramName);

        // 2. 尝试从header里读取
        if (ObjectUtil.isEmpty(paramValue)) {
            paramValue = request.header(paramName);
        }
        // 3. 尝试从cookie里读取
        if (ObjectUtil.isEmpty(paramValue)) {
            paramValue = request.cookie(paramName);
        }
        // 4. 返回
        return paramValue;
    }

    public static Context getRequest() {
        Context context;
        try {
            context = Context.current();
        } catch (Exception e) {
            log.error(">>> 非Web上下文无法获取Request：", e);
            throw new SystemException("非Web上下文无法获取Request");
        }
        if (context == null) {
            throw new SystemException("非Web上下文无法获取Request");
        } else {
            return context;
        }
    }

    public static boolean isWeb() {
        return Context.current() != null;
    }
}
